package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.OrderConfigMapper;
import com.qingcheng.dao.OrderItemMapper;
import com.qingcheng.dao.OrderLogMapper;
import com.qingcheng.dao.OrderMapper;
import com.qingcheng.entity.OrderOrderItems;
import com.qingcheng.entity.PageResult;
import com.qingcheng.entity.Split;
import com.qingcheng.pojo.order.Order;
import com.qingcheng.pojo.order.OrderConfig;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.pojo.order.OrderLog;
import com.qingcheng.pojo.seckill.SeckillOrder;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.service.seckill.SeckillOrderService;
import com.qingcheng.util.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.naming.Name;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderConfigMapper orderConfigMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private OrderLogMapper orderLogMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 返回全部记录
     *
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 条件查询
     *
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        List<Order> orders = orderMapper.selectByExample(example);
        return orders;
    }

    /**
     * 分页+条件查询
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }


    @Reference
    private SkuService skuService;
    @Autowired
    private CartService cartService;

    /**
     * 新增
     *
     * @param order
     */
    public Map<String, Object> add(Order order) {
        //获取购物车(刷新单价)
        List<Map<String, Object>> oderItemList = cartService.findNewOrderItemList(order.getUsername());
        // 获取选中的购物车
        List<OrderItem> orderItems = oderItemList.stream().filter(cart -> (boolean) cart.get("checked"))
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());
        // 扣减库存
        if (!skuService.deductionStock(orderItems)){
            //说明扣除失败
            throw new RuntimeException("库存不足");
        }

        try {
            // 保存订单主表
            order.setId(idWorker.nextId()+"");
            // 合计数计算
            IntStream numStream = orderItems.stream().mapToInt(OrderItem::getNum);
            IntStream moneyStream = orderItems.stream().mapToInt(OrderItem::getMoney);
            int totalNum=numStream.sum();//总数量
            int totalMoney=moneyStream.sum();//订单总金额
            int preMoney = cartService.preferential(order.getUsername()); //计算优惠金额
            order.setTotalNum(totalNum);//总数量
            order.setTotalMoney(totalMoney);//总金额
            order.setPreMoney(preMoney);//优惠金额
            order.setPayMoney(totalMoney-preMoney);//支付金额=总金额-优惠金额
            order.setCreateTime(new Date());//订单创建日期
            order.setOrderStatus("0"); // 订单状态
            order.setPayStatus("0"); // 支付状态：未支付
            order.setConsignStatus("0"); //发货状态：未发货
            orderMapper.insert(order);
            double proportion = (double)order.getPayMoney()/totalMoney;
            //保存订单明细
            for(OrderItem orderItem:orderItems){
                orderItem.setOrderId(order.getId());//订单主表ID
                orderItem.setId(idWorker.nextId()+"");
                orderItem.setPayMoney( (int)(orderItem.getMoney()* proportion) );//支付金额
                orderItemMapper.insert(orderItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //发送回滚信息
            rabbitTemplate.convertAndSend("","queue.skuback",JSON.toJSONString(orderItems));
            System.out.println("发送队列信息成功");
            throw  new RuntimeException("订单创建失败");
        }
        //清除选中的购物车
        cartService.deleteCheckedCart(order.getUsername());
        //返回订单号和支付的金额
        Map<String, Object> map=new HashMap();
        map.put("ordersn", order.getId() );
        map.put("money",order.getPayMoney());
        return map;



    }

    /**
     * 修改
     *
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据ID查询Order OrderItem 封装对象
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public OrderOrderItems findOrderOrderItemsById(String id) {
        OrderOrderItems orderOrderItems = new OrderOrderItems();
        Order order = orderMapper.selectByPrimaryKey(id);
        Example ex = new Example(OrderItem.class);
        Example.Criteria criteria = ex.createCriteria();
        criteria.andEqualTo("orderId", id);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(ex);
        orderOrderItems.setOrder(order);
        orderOrderItems.setOrderItems(orderItems);
        return orderOrderItems;
    }

    /**
     * 根据前端传输过来的List<Order> 批量发货
     */
    @Override
    @Transactional
    public void batchSend(List<Order> orders) {
        for (Order order : orders) {
            //判断物流公司和运单号是否为空
            if (order.getShippingName() == null || order.getShippingCode() == null) {
                throw new RuntimeException("物流公司或运单号为空，请填写物流公司或填写单号");
            }
        }
        for (Order order : orders) {
            order.setOrderStatus("3");
            order.setConsignStatus("2");
            order.setConsignTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
            //日志功能

            OrderLog orderLog = new OrderLog();
            orderLog.setId(Long.toString(new IdWorker().nextId()));
            orderLog.setOperater("wuyanzu");
            orderLog.setOperateTime(order.getConsignTime());
            orderLog.setOrderId(order.getId());
            orderLog.setOrderStatus(order.getOrderStatus());
            orderLog.setPayStatus(order.getPayStatus());
            orderLog.setConsignStatus(order.getConsignStatus());
            orderLog.setRemarks(order.getBuyerMessage());
            orderLogMapper.insertSelective(orderLog);
        }


    }

    /**
     * 订单超时处理
     */
    @Override
    @Transactional
    public void orderTimeOutLogic() {
        //订单超时未付款 自动关闭
        //查询超时时间         
        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);
        Integer orderTimeout = orderConfig.getOrderTimeout();
        //超时时间 （分） 60
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(orderTimeout);//得到超时的时间点
        //设置查询条件
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThan("createTime", localDateTime);//创建时间小于超时 时间         
        criteria.andEqualTo("orderStatus", "0");//未付款的
        criteria.andEqualTo("isDelete", "0");//未删除的
        //查询超时订单
        List<Order> orders = orderMapper.selectByExample(example);
        for (Order order : orders) {
            //记录订单变动日志             
            OrderLog orderLog = new OrderLog();
            orderLog.setOperater("system");
            // 系统
            orderLog.setOperateTime(new Date());//当前日期
            orderLog.setOrderStatus("4");
            orderLog.setPayStatus(order.getPayStatus());
            orderLog.setConsignStatus(order.getConsignStatus());
            orderLog.setRemarks("超时订单，系统自动关闭");
            orderLog.setOrderId(order.getId());
            orderLogMapper.insert(orderLog);
            //更改订单状态             
            order.setOrderStatus("4");
            order.setCloseTime(new Date());//关闭日期
            orderMapper.updateByPrimaryKeySelective(order);
        }

    }

    /**
     * 合并订单
     *
     * @param orderId1 主
     * @param orderId2 从
     */
    @Override
    public void merge(String orderId1, String orderId2) {
        //根据传输过来的ID查找Order与OrderItems
        Order order1 = orderMapper.selectByPrimaryKey(orderId1);
        /*Example ex1=new Example(OrderItem.class);
        Example.Criteria criteria1 = ex1.createCriteria();
        criteria1.andEqualTo("orderId",order1);
        List<OrderItem> orderItems1 = orderItemMapper.selectByExample(ex1);*/
        Order order2 = orderMapper.selectByPrimaryKey(orderId2);
        Example ex2 = new Example(OrderItem.class);
        Example.Criteria criteria2 = ex2.createCriteria();
        criteria2.andEqualTo("orderId", orderId2);
        List<OrderItem> orderItems2 = orderItemMapper.selectByExample(ex2);


        //将从表的详细订单指定的订单ID改为主表订单ID
        for (OrderItem orderItem : orderItems2) {
            orderItem.setOrderId(orderId1);
            orderItemMapper.updateByPrimaryKeySelective(orderItem);
        }
        //合并订单需要修改数量，金额，邮费，实付金额，订单更新时间
        int totalNum = order1.getTotalNum() + order2.getTotalNum();
        int totalMoney = order1.getTotalMoney() + order2.getTotalMoney();
        int postFee = order1.getPostFee() + order2.getPostFee();
        int payMoney = order1.getPayMoney() + order2.getPayMoney();
        Date updateTime = new Date();
        //新建一个Order对象使ID为主订单ID
        /*Order order = new Order();*/
        order1.setId(orderId1);
        order1.setTotalMoney(totalMoney);
        order1.setTotalNum(totalNum);
        order1.setPostFee(postFee);
        order1.setPayMoney(payMoney);
        order1.setUpdateTime(updateTime);
        orderMapper.updateByPrimaryKeySelective(order1);
        //删除order2
        order2.setIsDelete("1");
        orderMapper.updateByPrimaryKeySelective(order2);
        //日志功能
        OrderLog orderLog = new OrderLog();
        orderLog.setId(Long.toString(new IdWorker().nextId()));
        orderLog.setOperater("wuyanzu");
        orderLog.setOperateTime(order1.getConsignTime());
        orderLog.setOrderId(order1.getId());
        orderLog.setOrderStatus(order1.getOrderStatus());
        orderLog.setPayStatus(order1.getPayStatus());
        orderLog.setConsignStatus(order1.getConsignStatus());
        orderLog.setRemarks(order1.getId() + "合并" + order2.getId());
        orderLogMapper.insertSelective(orderLog);

    }

    /**
     * 分割订单
     *
     * @param orderItems
     */
    @Override
    public void split(List<OrderItem> orderItems) {
        //查询主订单ID
        OrderItem orderItem = orderItems.get(0);
        String orderId = orderItem.getOrderId();
        //查询主订单
        Order order = orderMapper.selectByPrimaryKey(orderId);
        //创建一个ID
        String id1 = Long.toString(idWorker.nextId());
        //记录订单需要修改数量，金额，邮费，实付金额，订单更新时间
        int totalNum = orderItems.size();
        int totalMoney = 0;
        int postFee = 0;
        int payMoney = 0;
        for (OrderItem item : orderItems) {
            totalMoney += item.getMoney();
            postFee += item.getPostFee();
            payMoney += item.getPayMoney();
            item.setOrderId(id1);
        }
        //根据查询出来的主订单复制信息更改信息
        Order order1 = new Order();
        BeanUtils.copyProperties(order1, order);
        order1.setId(id1);
        Date date = new Date();
        order1.setUpdateTime(date);
        order1.setCreateTime(date);
        order1.setTotalNum(totalNum);
        order1.setPayMoney(payMoney);
        order1.setPostFee(postFee);
        order1.setTotalMoney(totalMoney);
        orderMapper.updateByPrimaryKeySelective(order1);
        //更改主订单分离之后的信息
        order.setTotalMoney(order.getTotalMoney() - totalMoney);
        order.setTotalNum(order.getTotalNum() - totalNum);
        order.setPostFee(order.getPostFee() - postFee);
        order.setPayMoney(order.getPayMoney() - payMoney);
        order.setUpdateTime(date);
        orderMapper.updateByPrimaryKeySelective(order);


    }

    /**
     * 根据用户名查询用户订单信息
     *
     * @param searchMap 用户名
     * @param page      开始页
     * @param size      分页大小
     * @return
     */
    @Override
    public PageResult<OrderOrderItems> findPayPage(Map<String, Object> searchMap, int page, int size) {

        String username = (String) searchMap.get("username");
        if (username == null)
            return null;

        PageHelper.startPage(page, size);
        Example ex = new Example(Order.class);
        Example.Criteria cr = ex.createCriteria();
        cr.andEqualTo("username", username);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(ex);

        if (orders == null)
            return null;

        List<OrderOrderItems> orderOrderItemList = new ArrayList<>();
        for (Order order : orders) {
            Example example = new Example(OrderItem.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("orderId", order.getId());

            orderOrderItemList.add(new OrderOrderItems(order, orderItemMapper.selectByExample(example)));
        }

        return new PageResult<OrderOrderItems>(orders.getTotal(), orderOrderItemList);

    }

    /**
     * @param orderId
     * @param transactionId
     */
    @Override
    @Transactional
    public void updatePayStatus(String orderId, String transactionId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if(order!=null && "0".equals(order.getPayStatus())){ //存在订单且状态为0
            order.setPayStatus("1");
            order.setOrderStatus("1");
            order.setUpdateTime(new Date());
            order.setPayTime(new Date());
            order.setTransactionId(transactionId);//微信返回的交易流水号
            orderMapper.updateByPrimaryKeySelective(order);
            //记录订单变动日志

            OrderLog orderLog=new OrderLog();
            orderLog.setId(idWorker.nextId()+"");
            orderLog.setOperater("system");// 系统
            orderLog.setOperateTime(new Date());//当前日期
            orderLog.setOrderStatus("1");
            orderLog.setPayStatus("1");
            orderLog.setRemarks("支付流水号"+transactionId);
            orderLog.setOrderId(order.getId());
            orderLogMapper.insert(orderLog);
        }
    }
@Reference
private SeckillOrderService seckillOrderService;
    /**
     * 根据用户名查找所有订单信息
     * @param username
     * @return
     */
    @Override
    public Map<String,Object> queryOrderListByUsername(String username) {
        //创建一个map
        Map<String,Object> orderMap=new HashMap<String,Object>();
        //根据用户名先查询普通订单
        Example example=new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        criteria.andEqualTo("isDelete","0");//未删除的订单
        List<Order> orderList = orderMapper.selectByExample(example);
        orderMap.put("order",orderList);
        //根据用户名查询该用户的秒杀订单
        List<SeckillOrder> seckillOrders = seckillOrderService.querySeckillOrderListByUsername(username);

        orderMap.put("seckillOrder",seckillOrders);
        return orderMap;
    }
    /**
     * 根据商品id查询订单详情
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderOrderItems findOneOrder(String orderId, String username) {

        if (orderId == null)
            return null;

        Order order = orderMapper.selectByPrimaryKey(orderId);

        if (order==null)
            return null;

        if (!username.equals(order.getUsername()))
            throw new RuntimeException("用户参数非法");

        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", order.getId());

        OrderOrderItems orderOrderItems = new OrderOrderItems(order,orderItemMapper.selectByExample(example));
        return orderOrderItems;
    }


    /**
     * 构建查询条件
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 订单id
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andLike("id", "%" + searchMap.get("id") + "%");
            }
            // 支付类型，1、在线支付、0 货到付款
            if (searchMap.get("payType") != null && !"".equals(searchMap.get("payType"))) {
                criteria.andLike("payType", "%" + searchMap.get("payType") + "%");
            }
            // 物流名称
            if (searchMap.get("shippingName") != null && !"".equals(searchMap.get("shippingName"))) {
                criteria.andLike("shippingName", "%" + searchMap.get("shippingName") + "%");
            }
            // 物流单号
            if (searchMap.get("shippingCode") != null && !"".equals(searchMap.get("shippingCode"))) {
                criteria.andLike("shippingCode", "%" + searchMap.get("shippingCode") + "%");
            }
            // 用户名称
            if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                criteria.andEqualTo("username", searchMap.get("username"));
            }
            // 买家留言
            if (searchMap.get("buyerMessage") != null && !"".equals(searchMap.get("buyerMessage"))) {
                criteria.andLike("buyerMessage", "%" + searchMap.get("buyerMessage") + "%");
            }
            // 是否评价
            if (searchMap.get("buyerRate") != null && !"".equals(searchMap.get("buyerRate"))) {
                criteria.andLike("buyerRate", "%" + searchMap.get("buyerRate") + "%");
            }
            // 收货人
            if (searchMap.get("receiverContact") != null && !"".equals(searchMap.get("receiverContact"))) {
                criteria.andLike("receiverContact", "%" + searchMap.get("receiverContact") + "%");
            }
            // 收货人手机
            if (searchMap.get("receiverMobile") != null && !"".equals(searchMap.get("receiverMobile"))) {
                criteria.andLike("receiverMobile", "%" + searchMap.get("receiverMobile") + "%");
            }
            // 收货人地址
            if (searchMap.get("receiverAddress") != null && !"".equals(searchMap.get("receiverAddress"))) {
                criteria.andLike("receiverAddress", "%" + searchMap.get("receiverAddress") + "%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if (searchMap.get("sourceType") != null && !"".equals(searchMap.get("sourceType"))) {
                criteria.andLike("sourceType", "%" + searchMap.get("sourceType") + "%");
            }
            // 交易流水号
            if (searchMap.get("transactionId") != null && !"".equals(searchMap.get("transactionId"))) {
                criteria.andLike("transactionId", "%" + searchMap.get("transactionId") + "%");
            }
            // 订单状态
            if (searchMap.get("orderStatus") != null && !"".equals(searchMap.get("orderStatus"))) {
                criteria.andLike("orderStatus", "%" + searchMap.get("orderStatus") + "%");
            }
            // 支付状态
            if (searchMap.get("payStatus") != null && !"".equals(searchMap.get("payStatus"))) {
                criteria.andLike("payStatus", "%" + searchMap.get("payStatus") + "%");
            }
            // 发货状态
            if (searchMap.get("consignStatus") != null && !"".equals(searchMap.get("consignStatus"))) {
                criteria.andLike("consignStatus", "%" + searchMap.get("consignStatus") + "%");
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andLike("isDelete", "%" + searchMap.get("isDelete") + "%");
            }

            // 数量合计
            if (searchMap.get("totalNum") != null) {
                criteria.andEqualTo("totalNum", searchMap.get("totalNum"));
            }
            // 金额合计
            if (searchMap.get("totalMoney") != null) {
                criteria.andEqualTo("totalMoney", searchMap.get("totalMoney"));
            }
            // 优惠金额
            if (searchMap.get("preMoney") != null) {
                criteria.andEqualTo("preMoney", searchMap.get("preMoney"));
            }
            // 邮费
            if (searchMap.get("postFee") != null) {
                criteria.andEqualTo("postFee", searchMap.get("postFee"));
            }
            // 实付金额
            if (searchMap.get("payMoney") != null) {
                criteria.andEqualTo("payMoney", searchMap.get("payMoney"));
            }
            if (searchMap.get("ids") != null) {
                criteria.andIn("id", Arrays.asList(JSON.parseObject((String) searchMap.get("ids"), String[].class)));
            }

        }
        return example;
    }

}
